package org.news.web.controller.app;

import cn.dev33.satoken.annotation.SaIgnore;
import com.dtflys.forest.annotation.Get;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.web.core.BaseController;
import org.news.web.domain.bo.UsersBo;
import org.news.web.domain.bo.UsersQTBo;
import org.news.web.domain.vo.UsersVo;
import org.news.web.redis.RedisConstant;
import org.news.web.service.IUsersService;
import org.news.web.utils.UserInfoInterceptorUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/home")
@SaIgnore
public class LoginController extends BaseController {


    private final IUsersService usersService;


    /**
     * 登录  返回成功信息 data里面带有 redis 用户信息
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody UsersQTBo bo){
        return R.ok(usersService.login(bo));
    }


    /**
     * 注册 返回成功信息
     */

    @PostMapping("/register")
    public R<String> register(@RequestBody UsersQTBo bo){

        return R.ok(usersService.register(bo));
    }

    @GetMapping("/exit")
    public R<String> exit(HttpServletRequest request){
//        把用户信息在redis中删除
        Boolean flag = UserInfoInterceptorUtils.CheckUserInfoKey(request);
        if(!flag){
            throw new ServiceException("用户信息失效！");
        }
        String key = request.getHeader("Authorization");
        RedisUtils.deleteObject(RedisConstant.USER_KEY+":"+key);
        return R.ok("退出成功！");
    }

    /**
     * 获取用户个人信息  用redis key去进行获取
     * key 在头文件中携带
     * @param
     * @return
     */
    @GetMapping("/user")
    public R<UsersVo> getUserInfo(HttpServletRequest request){
        Boolean flag = UserInfoInterceptorUtils.CheckUserInfoKey(request);
        if(!flag){
            throw new ServiceException("用户信息失效！");
        }
        String key = request.getHeader("Authorization");
        return R.ok(usersService.getUserInfo(key));
    }



    @GetMapping("/code/{phone}")
    public R<String> sendCode(@PathVariable("phone")String phone){
        return R.ok(usersService.sendCode(phone));
    }
}
